#!/usr/bin/env python

import os,sys,time

import DebugMsgDef

DATAFILE_DELIMETER='	'

def ConvertTime(timestr):
	return int(time.mktime(time.strptime('2010-02-07 19:05:40','%Y-%m-%d %H:%M:%S')))

def findMessageByType(msgList, type):
	res=[];
	for msg in msgList:
		if msg.getType() == type:
			res.append(msg)
	return res

def main():
	# a dict of all messages. Key:Mote ID; value:list of messages.
	msgMap={}
	totalMessages=0
	if len(sys.argv) < 2:
		usage()
		sys.exit(0)

	datafile = open(sys.argv[1])
	print 'data file opened. Processing...'
	datafile.readline()

	# main reading loop
	for dline in datafile:
		darr = dline.split(DATAFILE_DELIMETER)
		motelab_seq       = darr[19]
		mote_id           = darr[18]
		insert_time       = ConvertTime(darr[17])

		msg_uid           = darr[4]
		origin            = darr[5]
		src               = darr[6]
		dest              = darr[7]
		etx               = darr[8]

		hopcount          = darr[10]
		metric            = darr[11]

		seqno             = darr[15]
		type              = darr[16]

		msg = DebugMsgDef.CtpDebugMsg(type,msg_uid,origin,src,dest,etx,hopcount,metric,seqno,insert_time,mote_id,motelab_seq)
		totalMessages=totalMessages+1

		# now add msgs to the msgMap
		mote_id = int(mote_id)
		if mote_id in msgMap:
			msgMap[mote_id].append(msg)
		else:
			msgMap[mote_id]=[]
			msgMap[mote_id].append(msg)

	datafile.close()
	for id in msgMap.keys():
		print 'Mote', id, 'sent', len(msgMap[id]), 'messages.'
	print 'Found', len(msgMap), 'mote(s) total.'

	print msgMap.keys()

	# just for test
	id = int(input('Enter mote ID: '))
	tp = int(input('Enter message type: '))
	ml = findMessageByType(msgMap[id],tp)
	for msg in ml:
		msg.printSelf()


def usage():
	print 'ReadMotelabData.py <data file path (.dat file only)>'

if __name__ == '__main__': main()

